<script setup lang="ts">
import type { IOrder } from '@/api/interface/rescue/order/order'
import { computed, ref, watch } from 'vue'
import { getOrderDetailApi } from '@/api/modules/rescue/order/order'
import OrderReviewStatusShow from '@/components/rescue/OrderReviewStatusShow.vue'
import { OrderReviewStatus } from '@/enums/rescue/OrderReviewStatus'

interface Props {
  /** 是否显示弹窗 */
  modelValue: boolean
  /** 订单ID */
  orderId?: number
}

// 定义组件名称
defineOptions({
  name: 'OrderDetail',
})

const props = defineProps<Props>()

const emit = defineEmits<{
  (e: 'update:modelValue', value: boolean): void
}>()

// 状态管理
const loading = ref(false)
const orderData = ref<IOrder.OrderVO | null>(null)

// 计算属性
const visible = computed({
  get: () => props.modelValue,
  set: (value: boolean) => {
    emit('update:modelValue', value)
  },
})

// 获取状态名称
function getStatusName(statusCode: string) {
  const statusItem = Object.values(OrderReviewStatus).find((item) => item.code === statusCode)
  return statusItem?.name || statusCode
}

// 格式化时间
function formatTime(timeStr: string) {
  if (!timeStr) return ''
  const date = new Date(timeStr)
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  const hours = String(date.getHours()).padStart(2, '0')
  const minutes = String(date.getMinutes()).padStart(2, '0')
  return `${year}-${month}-${day} ${hours}:${minutes}`
}

// 获取订单详情
async function fetchOrderDetail() {
  if (!props.orderId) return

  try {
    loading.value = true
    const result = await getOrderDetailApi(props.orderId)
    orderData.value = result.data
    console.log('订单详情数据:', result.data) // 调试用
  } catch (error) {
    console.error('获取订单详情失败:', error)
    uni.showToast({
      title: '获取订单详情失败',
      icon: 'none',
    })
  } finally {
    loading.value = false
  }
}

// 关闭弹窗
function handleClose() {
  visible.value = false
  // 清空数据
  orderData.value = null
}

// 监听弹窗显示状态和订单ID变化
watch(
  () => [props.modelValue, props.orderId],
  ([show, orderId]) => {
    if (show && orderId) {
      fetchOrderDetail()
    }
  },
  { immediate: true },
)
</script>

<template>
  <wd-popup
    v-model="visible"
    position="bottom"
    :safe-area-inset-bottom="true"
    class="order-detail-popup"
    @close="handleClose"
  >
    <view class="detail-container">
      <!-- 头部 -->
      <view class="detail-header">
        <view class="header-left">
          <wd-icon name="arrow-left" size="20px" @tap="handleClose" />
        </view>
        <text class="detail-title">订单详情</text>
        <view class="header-right">
          <wd-icon name="close" size="20px" @tap="handleClose" />
        </view>
      </view>

      <!-- 加载状态 -->
      <view v-if="loading" class="detail-loading">
        <wd-loading size="32px" />
        <text class="loading-text">加载详情中...</text>
      </view>

      <!-- 详情内容 -->
      <scroll-view v-else-if="orderData" class="detail-content" scroll-y enhanced>
        <!-- 基本信息卡片 -->
        <view class="info-card">
          <view class="card-header">
            <wd-icon name="info-circle" size="18px" color="#007AFF" />
            <text class="card-title">基本信息</text>
          </view>
          <view class="card-content">
            <view class="info-row">
              <text class="info-label">订单编号</text>
              <text class="info-value">
                {{ orderData.orderNumber }}
              </text>
            </view>
            <view class="info-row">
              <text class="info-label">任务编号</text>
              <text class="info-value">
                {{ orderData.workNumber }}
              </text>
            </view>
            <view class="info-row">
              <text class="info-label">申请原因</text>
              <text class="info-value multiline">
                {{ orderData.reason }}
              </text>
            </view>
            <view v-if="orderData.remark" class="info-row">
              <text class="info-label">备注</text>
              <text class="info-value multiline">
                {{ orderData.remark }}
              </text>
            </view>
            <view class="info-row">
              <text class="info-label">申请时间</text>
              <text class="info-value">
                {{ formatTime(orderData.createTime) }}
              </text>
            </view>
            <view class="info-row">
              <text class="info-label">当前状态</text>
              <OrderReviewStatusShow :status="orderData.status" variant="filled" size="small" />
            </view>
            <view class="info-row">
              <text class="info-label">申请人</text>
              <text class="info-value">
                {{ orderData.applyName }}
              </text>
            </view>
            <view v-if="orderData.applyPhone" class="info-row">
              <text class="info-label">联系电话</text>
              <text class="info-value">
                {{ orderData.applyPhone }}
              </text>
            </view>
          </view>
        </view>

        <!-- 申请物资卡片 -->
        <view v-if="orderData.orderItems?.length" class="materials-card">
          <view class="card-header">
            <wd-icon name="package" size="18px" color="#34C759" />
            <text class="card-title">申请物资</text>
            <text class="item-count">{{ orderData.orderItems.length }} 类物资</text>
          </view>
          <view class="card-content">
            <view v-for="item in orderData.orderItems" :key="item.id" class="material-item">
              <view class="material-image">
                <image v-if="item.image" :src="item.image" mode="aspectFill" class="item-image" />
                <view v-else class="image-placeholder">
                  <wd-icon name="package" size="20px" color="#C7C7CC" />
                </view>
              </view>
              <view class="material-info">
                <text class="material-name">
                  {{ item.productName || 'N/A' }}
                </text>
                <text class="material-spec">
                  {{ item.skuName || 'N/A' }}
                </text>
                <view class="material-meta">
                  <text class="material-price">¥{{ item.price || 0 }}</text>
                  <text class="material-quantity">×{{ item.quantity || 0 }}</text>
                </view>
              </view>
              <view class="material-total">
                <text class="total-price">
                  ¥{{ ((item.price || 0) * (item.quantity || 0)).toFixed(2) }}
                </text>
              </view>
            </view>
          </view>

          <!-- 汇总信息 -->
          <view class="materials-summary">
            <view class="summary-row">
              <text class="summary-label">总数量</text>
              <text class="summary-value">{{ orderData.totalAmount || 0 }} 件</text>
            </view>
            <view class="summary-row total">
              <text class="summary-label">总金额</text>
              <text class="summary-value">¥{{ (orderData.totalPrice || 0).toFixed(2) }}</text>
            </view>
          </view>
        </view>

        <!-- 审批记录卡片 -->
        <view v-if="orderData.orderReviews?.length" class="reviews-card">
          <view class="card-header">
            <wd-icon name="check-circle" size="18px" color="#FF9500" />
            <text class="card-title">审批记录</text>
          </view>
          <view class="card-content">
            <view class="timeline">
              <view
                v-for="(review, index) in orderData.orderReviews"
                :key="review.id"
                class="timeline-item"
                :class="{ 'is-last': index === orderData.orderReviews.length - 1 }"
              >
                <view class="timeline-node">
                  <view class="node-dot" />
                  <view v-if="index !== orderData.orderReviews.length - 1" class="node-line" />
                </view>
                <view class="timeline-content">
                  <view class="review-header">
                    <text class="reviewer-name">
                      {{ review.reviewName }}
                    </text>
                    <text class="review-time">
                      {{ formatTime(review.createTime) }}
                    </text>
                  </view>
                  <view class="review-status">
                    <text class="status-change">
                      {{ getStatusName(review.originStatus) }} →
                      {{ getStatusName(review.targetStatus) }}
                    </text>
                  </view>
                  <text v-if="review.reviewOpinion" class="review-opinion">
                    {{ review.reviewOpinion }}
                  </text>
                  <text v-if="review.reviewPhone" class="review-phone">
                    📞 {{ review.reviewPhone }}
                  </text>
                </view>
              </view>
            </view>
          </view>
        </view>

        <!-- 底部间距 -->
        <view class="bottom-spacing" />
      </scroll-view>
    </view>
  </wd-popup>
</template>

<style lang="scss" scoped>
// 设计系统变量
$primary-color: #007aff;
$success-color: #34c759;
$warning-color: #ff9500;
$danger-color: #ff3b30;
$text-primary: #1d1d1f;
$text-secondary: #86868b;
$text-tertiary: #c7c7cc;
$bg-primary: #ffffff;
$bg-secondary: #f2f2f7;
$bg-tertiary: #ffffff;
$border-color: rgba(60, 60, 67, 0.36);
$card-radius: 16rpx;
$item-radius: 12rpx;

.order-detail-popup {
  .detail-container {
    background: $bg-primary;
    border-radius: 20rpx 20rpx 0 0;
    max-height: 85vh;
    display: flex;
    flex-direction: column;
    box-shadow: 0 -4rpx 20rpx rgba(0, 0, 0, 0.1);
  }

  .detail-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 16rpx 32rpx;
    border-bottom: 1px solid $border-color;
    background: rgba(255, 255, 255, 0.95);
    backdrop-filter: blur(20px);
    position: sticky;
    top: 0;
    z-index: 100;

    .header-left,
    .header-right {
      width: 60rpx;
      display: flex;
      justify-content: center;
      align-items: center;
    }

    .detail-title {
      font-size: 32rpx;
      font-weight: 600;
      color: $text-primary;
      text-align: center;
    }
  }

  .detail-loading {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    padding: 120rpx 40rpx;

    .loading-text {
      font-size: 28rpx;
      color: $text-secondary;
      margin-top: 24rpx;
    }
  }

  .detail-content {
    flex: 1;
    overflow-y: auto;
  }

  // 卡片通用样式
  .info-card,
  .materials-card,
  .reviews-card {
    background: $bg-tertiary;
    border-radius: $card-radius;
    margin-bottom: 24rpx;
    border: 1px solid rgba(0, 0, 0, 0.05);
    box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.04);
    overflow: hidden;
  }

  .card-header {
    display: flex;
    align-items: center;
    padding: 24rpx 24rpx 16rpx;
    gap: 12rpx;

    .card-title {
      font-size: 28rpx;
      font-weight: 600;
      color: $text-primary;
      flex: 1;
    }

    .item-count {
      font-size: 22rpx;
      color: $success-color;
      font-weight: 500;
    }
  }

  .card-content {
    padding: 0 24rpx 24rpx;
  }

  // 基本信息样式
  .info-row {
    display: flex;
    align-items: flex-start;
    padding: 16rpx 0;
    border-bottom: 1px solid rgba(0, 0, 0, 0.05);

    &:last-child {
      border-bottom: none;
    }

    .info-label {
      font-size: 26rpx;
      color: $text-secondary;
      min-width: 140rpx;
      margin-right: 20rpx;
      flex-shrink: 0;
    }

    .info-value {
      font-size: 26rpx;
      color: $text-primary;
      font-weight: 500;
      flex: 1;
      word-break: break-all;

      &.multiline {
        line-height: 1.5;
      }
    }
  }

  // 物资列表样式
  .material-item {
    display: flex;
    align-items: center;
    padding: 20rpx 0;
    border-bottom: 1px solid rgba(0, 0, 0, 0.05);
    gap: 16rpx;

    &:last-child {
      border-bottom: none;
    }

    .material-image {
      width: 80rpx;
      height: 80rpx;
      border-radius: $item-radius;
      overflow: hidden;
      flex-shrink: 0;
      background: $bg-secondary;

      .item-image {
        width: 100%;
        height: 100%;
        object-fit: cover;
      }

      .image-placeholder {
        width: 100%;
        height: 100%;
        display: flex;
        align-items: center;
        justify-content: center;
        background: $bg-secondary;
      }
    }

    .material-info {
      flex: 1;
      min-width: 0;

      .material-name {
        display: block;
        font-size: 28rpx;
        font-weight: 600;
        color: $text-primary;
        margin-bottom: 6rpx;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
      }

      .material-spec {
        display: block;
        font-size: 24rpx;
        color: $text-secondary;
        margin-bottom: 8rpx;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
      }

      .material-meta {
        display: flex;
        align-items: center;
        gap: 16rpx;

        .material-price {
          font-size: 22rpx;
          color: $success-color;
          font-weight: 500;
        }

        .material-quantity {
          font-size: 22rpx;
          color: $text-secondary;
          background: rgba(0, 122, 255, 0.1);
          padding: 4rpx 8rpx;
          border-radius: 8rpx;
        }
      }
    }

    .material-total {
      flex-shrink: 0;
      text-align: right;

      .total-price {
        font-size: 28rpx;
        font-weight: 600;
        color: $primary-color;
      }
    }
  }

  // 汇总信息样式
  .materials-summary {
    margin-top: 16rpx;
    padding: 20rpx;
    background: rgba(0, 122, 255, 0.05);
    border-radius: $item-radius;
    border: 1px solid rgba(0, 122, 255, 0.1);

    .summary-row {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 8rpx;

      &:last-child {
        margin-bottom: 0;
      }

      &.total {
        padding-top: 8rpx;
        border-top: 1px solid rgba(0, 122, 255, 0.2);

        .summary-label,
        .summary-value {
          font-weight: 600;
          color: $primary-color;
        }
      }

      .summary-label {
        font-size: 26rpx;
        color: $text-secondary;
      }

      .summary-value {
        font-size: 26rpx;
        color: $text-primary;
        font-weight: 500;
      }
    }
  }

  // 审批记录样式
  .timeline {
    position: relative;

    .timeline-item {
      display: flex;
      margin-bottom: 32rpx;

      &:last-child {
        margin-bottom: 0;
      }

      .timeline-node {
        position: relative;
        width: 40rpx;
        display: flex;
        flex-direction: column;
        align-items: center;
        margin-right: 20rpx;
        flex-shrink: 0;

        .node-dot {
          width: 16rpx;
          height: 16rpx;
          background: $primary-color;
          border-radius: 50%;
          border: 3px solid white;
          box-shadow: 0 0 0 2px $primary-color;
          z-index: 2;
        }

        .node-line {
          flex: 1;
          width: 2px;
          background: rgba(0, 122, 255, 0.2);
          margin-top: 8rpx;
          min-height: 40rpx;
        }
      }

      .timeline-content {
        flex: 1;
        background: rgba(255, 255, 255, 0.8);
        border-radius: $item-radius;
        padding: 20rpx;
        border: 1px solid rgba(0, 0, 0, 0.05);

        .review-header {
          display: flex;
          justify-content: space-between;
          align-items: center;
          margin-bottom: 12rpx;

          .reviewer-name {
            font-size: 26rpx;
            font-weight: 600;
            color: $text-primary;
          }

          .review-time {
            font-size: 22rpx;
            color: $text-secondary;
          }
        }

        .review-status {
          margin-bottom: 12rpx;

          .status-change {
            display: inline-block;
            background: rgba(0, 122, 255, 0.1);
            color: $primary-color;
            padding: 6rpx 12rpx;
            border-radius: 8rpx;
            font-size: 22rpx;
            font-weight: 500;
          }
        }

        .review-opinion {
          display: block;
          font-size: 24rpx;
          color: $text-primary;
          line-height: 1.5;
          background: rgba(52, 199, 89, 0.05);
          padding: 12rpx 16rpx;
          border-radius: 8rpx;
          border-left: 3px solid $success-color;
          margin-bottom: 8rpx;
        }

        .review-phone {
          font-size: 22rpx;
          color: $text-secondary;
        }
      }
    }
  }

  .bottom-spacing {
    height: 40rpx;
  }
}

// 响应式设计
@media (max-width: 750rpx) {
  .order-detail-popup {
    .detail-content {
      padding: 20rpx 24rpx 0;
    }

    .card-header,
    .card-content {
      padding-left: 20rpx;
      padding-right: 20rpx;
    }
  }
}

// 暗色模式支持
@media (prefers-color-scheme: dark) {
  .order-detail-popup {
    .detail-container {
      background: #1c1c1e;
    }

    .detail-header {
      background: rgba(28, 28, 30, 0.95);
      border-bottom-color: #48484a;
    }

    .info-card,
    .materials-card,
    .reviews-card {
      background: #2c2c2e;
      border-color: #48484a;
    }
  }
}
</style>
